<?php

namespace app\common\model;

use x\Xbase;

class Goods extends Xbase
{
    /**
     * 商品列表
     * @param  array $map 条件
     * @param  integer $o 排序类型
     * @param  integer $page 页数
     * @param  integer $limit 条数
     * @return [type]         [description]
     */
    public function lists($map = [], $o = 0, $page = 1, $limit = 20)
    {
        $w = where($map);
        $order = "";
        switch ($o) {
            case 1: //综合排序
                $order = "order by sort desc,id desc";
                break;
            case 2: //销量排序
                $order = "order by sales_volume desc,sort desc";
                break;
            case 3: //人气排序
                $order = "order by views desc,sales_volume desc";
                break;
            case 4://价格升序
                $order = "order by price desc,views desc";
                break;
            case 5://价格降序
                $order = "order by price asc,views desc";
                break;
            default:
                $order = "order by sort desc,id desc";

        }
        $sql = "select * from goods $w[0] {$order} " . limit($page, $limit);
        $rs = $this->db->query($sql, $w[1], '', true);
        return $rs;
    }

    /**
     * 推荐位商品
     * @param  [type] $rec_id 推荐位ID
     * @param  [type] $page   [description]
     * @param  [type] $limit  [description]
     * @return [type]         [description]
     */
    public function recLists( $page, $limit)
    {
        $rs = $this->db->find("goods_rec", 11);//PC端商品推荐位
        $sql = "select * from goods where rec_id like '%{$rs["id"]}%' and status = 0 order by sort limit 5";
        $rec_goods_list = $this->db->query($sql);

        return $rec_goods_list;
    }

    /**
     * 获取商品详情
     * @param type $goods_id
     */
    public function detail($goods_id)
    {
        $sql = "
        select
            b.*,a.title as p_title, a.price as p_price,a.views as p_views,a.goods_id, a.stock as p_stock,a.id as gid
        from
            goods_price a
        left join
            goods b
        on
            a.goods_id = b.id
        where
            a.id=?
        ";
        $rs = $this->db->query($sql,[$goods_id],1);
        return $rs;
    }

    /**
     * 获取商品详情
     * @param type $goods_id
     */
    public function priceDetail($goods_id)
    {
        $sql = "select *,g.title as goods_title from goods as g inner join goods_price as p on g.id = p.goods_id where p.id = ?";
        $rs = $this->db->query($sql, [$goods_id], 1);
        return $rs;
    }

    /**获取商品规格
     * @param $goods_id
     * @return mixed
     */
    public function attrList($goods_id)
    {
        return $this->db->query("select * from goods_price where goods_id = ?", [$goods_id]);
    }

    /**我的购物车
     * @return array
     */
    public function myCart()
    {
        $ids = [];
        $carts = get_cookie_arr("cart");
        $cart_arr = [];
        $cart_list = [];
        foreach ($carts as $k => $v) {
            $cart = explode("|", $v);
            $cart_arr[] = $cart;
            $ids[] = $cart[1];
        }
        if ($ids) {
            $cart_list = $this->db->query("select *,g.title goods_name from goods g inner join goods_price p on p.goods_id = g.id where p.id in (" . implode(',', $ids) . ")");
        }
        $d = ["cart_list" => $cart_list, "cart_arr" => $cart_arr];
        return $d;
    }

    //添加商品
    public function add($d)
    {
        $spec = htmlspecialchars_decode($d['spec']);
        $spec = json_decode($spec,true);
        if(!$spec){
            $spec = ['规格'=>[$d['title']]];
        }
        $spec_temp = $spec;
        asort($spec);
        $spec = json_encode($spec,JSON_UNESCAPED_UNICODE );
        $data = [
            'title' => $d['title'],
            'keyword' => $d['keyword'],
            'description' => $d['description'],
            'price' => $d['price'],
            'pic' => $d['pic'],
            'pics' => $d['pics'],
            'content' => isset($d['content']) ? $d['content'] : '',
            'attr' => $d['attr'],
            'spec' => htmlspecialchars($spec),
            'create_time' => time(),
            'cat_id' => $d['cat_id'],
            'shop_id' => $d['shop_id'],
            'status' => $d['status'],
            'postage' => $d['postage']
        ];
        //添加商品
        $this->db->begin();
        $mysql = [];
        $mysql[] = $id = $this->db->insert("goods", $data);
        m('Attachment','xcom')->imgSure('goods',$id,$data);
        //添加规格表数据，产品价格表goods_price
        $attr = $spec_temp;
        foreach ($attr as $k => $v) {
            $attr[$k] = implode(',', $v);
        }
        $temp = m('GoodsPrice', 'c')->CountAttr($attr);
        $arr = $temp['arr'];
        $goods_price = [];
        foreach ($arr as $title) {
            $stock = isset($d[$title . '_stock'][0]) ? (int)$d[$title . '_stock'][0] : 100;
            $price = isset($d[$title . '_price'][0]) ? (float)$d[$title . '_price'][0] : $data['price'];
            $tmp = [
                'goods_id' => $id,
                'title' => $title,
                'stock' => $stock,
                'price' => $price,
            ];
            $goods_price[] = $tmp;
        }
        $mysql[] = $this->db->insertAll("goods_price", $goods_price);
        $this->db->end($mysql);
        return $mysql;
    }

    /**
     *更新商品
     */
    public function edit($d)
    {
        $spec = htmlspecialchars_decode($d['spec']);
        $spec = json_decode($spec,true);
        if(!$spec){
            $spec = ['规格'=>[$d['title']]];
        }
        $spec_temp = $spec;
        asort($spec);
        $spec = json_encode($spec,JSON_UNESCAPED_UNICODE );
        $data = [
            'title' => $d['title'],
            'keyword' => $d['keyword'],
            'description' => $d['description'],
            'price' => $d['price'],
            'pic' => $d['pic'],
            'pics' => $d['pics'],
            'content' => isset($d['content']) ? $d['content'] : '',
            'spec' => htmlspecialchars($spec),
            'attr' => $d['attr'],
            'update_time' => time(),
            'cat_id' => $d['cat_id'],
            'shop_id' => $d['shop_id'],
            'id' => $d['id'],
            'status' => $d['status'],
            'postage' => $d['postage']
        ];
        //添加商品
        $rs = $this->db->update("goods", $data);
        m('Attachment','xcom')->imgSure('goods',$data['id'],$data);
        //添加规格表数据，产品价格表goods_price
        $attr = $spec_temp;
        foreach ($attr as $k => $v) {
            $attr[$k] = implode(',', $v);
        }
        $temp = m('GoodsPrice', 'c')->CountAttr($attr);
        $arr = $temp['arr'];
        $ids = [];
        foreach ($arr as $title) {
            $stock = isset($d[$title . '_stock'][0]) ? (int)$d[$title . '_stock'][0] : 100;
            $price = isset($d[$title . '_price'][0]) ? (float)$d[$title . '_price'][0] : $data['price'];
            $tmp = [
                'goods_id' => $d['id'],
                'title' => $title,
                'stock' => $stock,
                'price' => $price,
            ];
            $info = $this->db->query('select * from goods_price where  goods_id=? and title=?', [$data['id'], $title], 1);
            if ($info) {
                $tmp['id'] = $info['id'];
                $mysql[] = $this->db->update('goods_price', $tmp);
                $ids[] = $info['id'];
            } else {
                $mysql[] = $id = $this->db->insert('goods_price', $tmp);
                $ids[] = $id;
            }
        }
        //删除多余的规格
        if($ids){
            $ids = implode(",", $ids);
            $mysql[] = $this->db->query("delete from goods_price where id NOT IN (" . $ids . ") AND goods_id=?", [$data['id']]);
        }
        return $rs;
    }

    //修改库存添加销量
    public function updateStock($num,$goods_price_id){
        $re = $this->db->query('select * from goods_price where id = ?',[$goods_price_id],1);
        $data = [
            'stock' => $re['stock'] - $num,
            'sales_volume' => $re['sales_volume'] + $num,
        ];
        $this->db->update('goods_price',$data,['id=?',[$re['id']]]);
        $info = $this->db->query('select * from goods where id = ?',[$re['goods_id']],1);
        $goods_data = [
            'sales_volume' => $info['sales_volume'] + $num,
        ];
        $this->db->update('goods',$goods_data,['id=?',[$info['id']]]);
        return true;
    }
}
